onload = () => {
    loadCSS("../css/fontello.css", "bootstrap5-icon");
    loadCSS("../css/bootstrap5.min.css", "bootstrap5");
    loadCSS("../css/common.css", "common");
    loadScript("../js/bootstrap5.bundle.min.js")
        .then(() => loadScript("../js/crud.js")).then(() => {
        let detailQuery = {};
        let apReportOperator = new Crud({
            module: "ap",
            pk:"apStatementId",
            hasCheckbox: true,
            iterators: [],
            extendAttribute: [{name: "updatedBy", type: "userById"}, {
                name: "apStatementId",
                type: "apStatementDetail"
            }],
            opsButton: [{
                caption: "Create Report",
                "action": "modal",
                "param": "#dateRangeModal",
                class: "btn btn-primary",
                commit: form => {
                    let view = true;
                    form.elements["view"].forEach(i => {
                        if (i.checked) view = i.value
                    });
                    let url = `/ap/createStatement?billNo=${form.elements["billNo"].value.trim()}`;
                    url += `&view=${view}`;
                    ajax(url).then(data => {
                        showToast(`Upload successful: ${JSON.stringify(data.data)}`, "primary");
                        loadData();
                        let modalElement = document.getElementById("uploadQuoteFile");
                        const modal = bootstrap.Modal.getInstance(modalElement)
                            || new bootstrap.Modal(modalElement);
                        modal.hide();
                    })
                }
            }],
            rowBtn: ["delete"],
            search: [],
            listField: [{"caption": "ID", "field": "apStatementId"},
                {caption: "Bill #", "field": "billNo"},
                {caption: "Type", "field": "type"},
                {caption: "Waybill Count", "field": "waybillCount"},
                {caption: "Revenue", "field": "revenue", format: v => v / 100},
                {caption: "Cost", "field": "cost", format: v => v / 100},
                {caption: "Profit", "field": "profit", format: v => v / 100},
                {caption: "Profit Margin", "field": i => (i.profit * 100 / i.revenue).toFixed(2), format: v => v + "%"},
                {caption: "UpdateTime", "field": "createTime", format: str => subString(str,0,10)},
                {caption: "UpdatedBy", "field": "updatedBy_userById.userName"}],
            rowEvent: function (e, item, tr, outer) {
                detailQuery.apStatementId = item.apStatementId;
                outer.subTable["chargeTable"].load(item["apStatementId_apStatementDetail"]);
                canvas.show();
            },
            subTable: [{
                name: "chargeTable",
                tableId: "chargeTable",
                listField: [{"caption": "Tracking#", "field": "trackingNo"},
                    {"caption": "Customer", "field": "customer"},
                    {"caption": "Carrier", "field": "carrier"},
                    {"caption": "Revenue", "field": "revenue", format: str => str / 100},
                    {"caption": "Cost", "field": "cost", format: str => str / 100},
                    {"caption": "Profit", "field": "profit", format: str => str / 100},
                    {
                        "caption": "Profit Margin",
                        "field": (i) => (i.profit * 100 / i.revenue).toFixed(2),
                        format: str => str + "%"
                    },
                ],opsBtn: [{
                    caption: "Export",
                    class: "btn btn-primary",
                    callback: () => {
                        ajax(`/ap/statement/export`, {method: "POST", body: {data: detailQuery}}, function (data) {
                            if (data.data) {
                                showToast(`Click to <a href='${contentPath + "/file/download/" + data.data}'>download</a>`,-1);
                            }
                        });
                    }
                },{
                    caption: "Chart",
                    class: "btn btn-primary",
                    action:"modal",
                    param: "#chartModal",
                    callback: () => {

                    }
                }
                ]
            }],
            editFields: [
                {"name": "code", "placeHolder": "code", "required": "required"},
                {"name": "pk", "placeHolder": "PK in cargo wise", "required": "required"},
                {caption: "Full Name:", "name": "fullname", "placeHolder": "Full name", "required": "required"}
            ]
        });
        apReportOperator.init();
        apReportOperator.setCrudLink("delete","/ap/delete")
        function loadData() {
            apReportOperator.loadData();
        }

        const canvas = new bootstrap.Modal(document.getElementById('subTable'));
    }).catch((err) => console.error(err));
}
